package com.walala.dispatcher.executor;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import com.alibaba.fastjson.JSON;
import com.walala.dispatcher.annotion.ExecutorHandler;
import com.walala.dispatcher.global.Constant;
import com.walala.dispatcher.global.RequestType;
import com.walala.dispatcher.pojo.RequestMsg;
import com.walala.dispatcher.pojo.ServerInfo;
import com.walala.dispatcher.redis.RedisClient;

/**
 * 接入层上报
 */
@ExecutorHandler(requestType = RequestType.REPORT_CONNECTOR)
public class ConnectorReportExecutor extends DispatcherExecutor{
	
	private Logger logger = LoggerFactory.getLogger(ConnectorReportExecutor.class);
	
	public ConnectorReportExecutor(){
		this.type = RequestType.REPORT_CONNECTOR;;
	}

	public void dispatcher(ChannelHandlerContext ctx, DatagramPacket packet,RequestMsg requestMsg) {
		
		int requestType = requestMsg.getRequestType();
		if(requestType != RequestType.REPORT_CONNECTOR){
			logger.error("接入层上报请求类型非法：合法参数：[{}],非法参数:[{}]",RequestType.REPORT_CONNECTOR,requestType);
			return;
		}
		 
		String ipPort = requestMsg.getIpPort();
		if(StringUtils.isBlank(ipPort)){
			logger.error("接入层上报非法，地址为：[{}]",ipPort);
			return;
		}
		
		long now = System.currentTimeMillis();
		
		ServerInfo serverInfo = new ServerInfo();
		serverInfo.setIpPort(ipPort);
		serverInfo.setType(Constant.Server_Type.CONNECTOR.value);
		serverInfo.setUpdateTime(now);
		serverInfo.setStatus(Constant.Server_Status.OK.value);
		
		Jedis cluster = RedisClient.intance.getCluster();
		
		/*double weight = requestMsg.getWeight();
		
		if(weight < 0){
			weight = 0;
		} else {
			try {
				String serverStr = cluster.hget(Constant.RPC_WEIGHT_REDIS_KEY,ipPort);
				
				if (StringUtils.isNotBlank(serverStr)) {
					RpcServerStatus serverStatus = JSON.parseObject(serverStr, RpcServerStatus.class);
					double weightValue = serverStatus.getWeight();
					if (weightValue > 0) {
						weight = weightValue;
					}
				}

			} catch (Exception e) {
				logger.error("error:{}", e);
				return;
			}
		}
		serverInfo.setWeight(weight);*/
		try {
            cluster.hset(Constant.CONNECTOR_SERVER_INFO, ipPort, JSON.toJSONString(serverInfo));
            logger.info("connector上报,type:[{}],address:[{}]",requestType,ipPort);
        } catch (Exception e) {
            logger.error("connector上报异常,type:[{}],address:[{}]",requestType,ipPort);
        }
		String rspReportJson = JSON.toJSONString(requestMsg);
        try {
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(rspReportJson, CharsetUtil.UTF_8), packet.sender()));
            logger.info("服务端返回数据信息:{}", rspReportJson);
        } catch (Exception e) {
            //e.printStackTrace();
        	logger.error("服务端返回数据信息失败:{}", rspReportJson);
        }
        logger.info("connector上报成功,type:[{}],address:[{}]",requestType,ipPort);
		
	}

}
